package com.cssy.yd.logic.service.impl;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSONArray;
import com.byd.acegiext.domain.User;
import com.cssy.yd.logic.dao.LogicProGetApplyDAO;
import com.cssy.yd.logic.dao.LogicProGetApplyItemDAO;
import com.cssy.yd.logic.dao.LogicProGetDAO;
import com.cssy.yd.logic.dao.LogicProGetItemBatchDAO;
import com.cssy.yd.logic.dao.LogicProGetItemDAO;
import com.cssy.yd.logic.entity.LogicProGetApplyDO;
import com.cssy.yd.logic.entity.LogicProGetApplyItemDO;
import com.cssy.yd.logic.entity.LogicProGetDO;
import com.cssy.yd.logic.entity.LogicProGetItemBatchDO;
import com.cssy.yd.logic.entity.LogicProGetItemDO;
import com.cssy.yd.logic.entity.LogicWhAffDO;
import com.cssy.yd.logic.service.ILogicProGetService;
import com.cssy.yd.logic.service.ILogicWhAffStockService;
import com.plat.exception.SyBaseException;
import com.plat.helper.SearchCondition;
import com.plat.helper.SearchConditions;
import com.plat.helper.SearchResult;
import com.plat.util.DateUtils;
import com.plat.util.GlobalResLoader;
import com.plat.util.IDCodeTypeUtil;
import com.plat.util.SessionUtil;
import com.yuendong.sy.service.code.SyCodeType;
import com.yuendong.sy.po.code.SyCode;
import com.yuendong.sy.service.code.impl.SyCodeService;

@Service("logicProGetService")
public class LogicProGetServiceImpl implements ILogicProGetService {

	private static final Logger logger = Logger.getLogger(LogicProGetServiceImpl.class);

	@Resource(name = "logicProGetDAO")
	private LogicProGetDAO logicProGetDAO;

	@Resource(name = "logicProGetItemDAO")
	private LogicProGetItemDAO logicProGetItemDAO;

	@Resource(name = "logicProGetApplyItemDAO")
	private LogicProGetApplyItemDAO logicProGetApplyItemDAO;
		
	@Resource(name = "logicWhAffStockService")
	private ILogicWhAffStockService logicWhAffStockService;

	@Resource(name = "syCodeService")
	private SyCodeService syCodeService;
	
	@Resource(name = "logicProGetApplyDAO")
	private LogicProGetApplyDAO logicProGetApplyDAO;

	@Resource(name="logicProGetItemBatchDAO")
	private LogicProGetItemBatchDAO logicProGetItemBatchDAO;
	
	@Override
	public SearchResult findListByExample(SearchConditions scs)throws SyBaseException {
		SearchResult rs = new SearchResult(scs);
		List<LogicProGetDO> list = logicProGetDAO.find(scs);
		rs.setResults(list);
		rs.setRecordCount(logicProGetDAO.count(scs));// 添加分页计算 add by huang.xuming[2013-11-09]
		return rs;
	}

	@Override
	public Integer delete(String id, User user) throws SyBaseException {
		return logicProGetDAO.deleteLogicProGetDOByPrimaryKey(id);
	}

	@Override
	public Integer update(LogicProGetDO t, User user) throws SyBaseException {
		t.setDuuser(user.getName());
		t.setDutime(new Date());
		return logicProGetDAO.updateLogicProGetDO(t);
	}

	@Override
	public LogicProGetDO save(LogicProGetDO t, User user)
			throws SyBaseException {
		t.setDcruser(user.getName());
		t.setDctime(new Date());
		logicProGetDAO.insertLogicProGetDO(t);
		return null;
	}

	@Override
	public LogicProGetDO findListById(String id) throws SyBaseException {
		return logicProGetDAO.findLogicProGetDOByPrimaryKey(id);
	}

	@Override
	public void proGetSave(HttpServletRequest request, LogicProGetDO curAP)
			throws SyBaseException {
		try {
			String itemdata = request.getParameter("addressInfos");
			List<LogicProGetItemDO> swItemList = JSONArray.parseArray(itemdata,LogicProGetItemDO.class);
			/*
			 * 获取操作 0为保存(草稿状态) 
			 * 1为提交(待审核状态) 
			 * 2为二级结案(提交二级结案) 
			 * 3为二级驳回到草稿
			 */
			String paramflag = request.getParameter("billStatus");
			if ("0".equals(paramflag)) {
				
				//---start 判断单据是否存在未完成处理的记录
				if(StringUtils.isBlank(curAP.getOriCode())){
					throw new SyBaseException("领料申请单编号参数为空");
				}
				SearchConditions scs = new SearchConditions();
				scs.addCondition("ori_code", curAP.getOriCode(), SearchCondition.OP_EQUAL);
				scs.addCondition("bill_status", "2", SearchCondition.OP_NOTEQUAL);
				Integer count = logicProGetDAO.count(scs);
				if(null != count && count > 0){
					throw new SyBaseException(curAP.getOriCode()+"领料申请单存在未处理完的领料出库单");
				}
				//---end 判断单据是否存在未完成处理的记录
				
				/* 新增 设置状态billstatus= 0 */
				String id = IDCodeTypeUtil.getId();
				curAP.setBillStatus(Short.parseShort(paramflag));
				curAP.setId(id);
				curAP.setGetProCode(syCodeService.getCode("LL","LL",SyCode.DATE_YYMM,5));
				curAP.setDcruser(SessionUtil.getUser(request).getName());
				curAP.setDctime(new Date());
				// 日期转换处理
				String deliveryDate = request.getParameter("consumingtime");
				if (StringUtils.isNotBlank(deliveryDate)) {
					curAP.setConsumingtime(DateUtils.stringToDate(deliveryDate));
				}
				logicProGetDAO.insertLogicProGetDO(curAP);
				 for(int i=0;i<swItemList.size();i++){
					 String itemId =IDCodeTypeUtil.getId();
					 swItemList.get(i).setGetProId(id);
					 swItemList.get(i).setId(itemId);
					 logicProGetItemDAO.insertLogicProGetItemDO(swItemList.get(i));
					 if(swItemList.get(i).getItemBatch() != null && !"".equals(swItemList.get(i).getItemBatch().trim())){
							List<LogicProGetItemBatchDO> itemBatchDOs = JSONArray.parseArray(swItemList.get(i).getItemBatch(),LogicProGetItemBatchDO.class);
							for (int j = 0; j < itemBatchDOs.size(); j++) {
								itemBatchDOs.get(j).setId(IDCodeTypeUtil.getId());
								itemBatchDOs.get(j).setProGetItemid(itemId);
								logicProGetItemBatchDAO.insertLogicProGetItemBatchDO(itemBatchDOs.get(j));
							}
						}
				 }

			}
			if("1".equals(paramflag)){// 修改并提交到二级审核
				int result = 0;
				curAP.setBillStatus(Short.parseShort(paramflag));
				curAP.setDutime(new Date());
				curAP.setDuuser(SessionUtil.getUser(request).getName());
				// 日期转换处理
				String deliveryDate = request.getParameter("consumingtime");
				if (StringUtils.isNotBlank(deliveryDate)) {
					curAP.setConsumingtime(DateUtils.stringToDate(deliveryDate));
				}
				result = logicProGetDAO.updateLogicProGetDO(curAP);
				if(1==result){
					SearchConditions scs = new SearchConditions();
					scs.addCondition("get_pro_id",curAP.getId(),SearchCondition.OP_EQUAL);
					scs.setRemovedProperty(null);
					scs.setLimitPage(false);
					List<LogicProGetItemDO> logicProGetItemDO = logicProGetItemDAO.find(scs);
					if(logicProGetItemDO != null &&  logicProGetItemDO.size() > 0){
						for (int i = 0; i < logicProGetItemDO.size(); i++) {
							logicProGetItemBatchDAO.deleteByproGetItemId(logicProGetItemDO.get(i).getId());
						}
					}
					logicProGetItemDAO.deleteLogicProGetItemPrimaryKey(curAP.getId());
					for(int i=0;i<swItemList.size();i++){
						String itemId =IDCodeTypeUtil.getId();
						 swItemList.get(i).setGetProId(curAP.getId());
						 swItemList.get(i).setId(itemId);
						 logicProGetItemDAO.insertLogicProGetItemDO(swItemList.get(i));
						 if(swItemList.get(i).getItemBatch() != null && !"".equals(swItemList.get(i).getItemBatch().trim())){
								List<LogicProGetItemBatchDO> itemBatchDOs = JSONArray.parseArray(swItemList.get(i).getItemBatch(),LogicProGetItemBatchDO.class);
								for (int j = 0; j < itemBatchDOs.size(); j++) {
									itemBatchDOs.get(j).setId(IDCodeTypeUtil.getId());
									itemBatchDOs.get(j).setProGetItemid(itemId);
									logicProGetItemBatchDAO.insertLogicProGetItemBatchDO(itemBatchDOs.get(j));
								}
							}
					 }
				}
			}
			if("2".equals(paramflag)){// 二级审核完结-出库
				int result = 0;
				curAP.setBillStatus(Short.parseShort(paramflag));
				curAP.setDutime(new Date());
				curAP.setDuuser(SessionUtil.getUser(request).getName());
				
				//查询原始领料申请单及其明细
				LogicProGetDO proget = logicProGetDAO.findLogicProGetDOByPrimaryKey(curAP.getId());
				SearchConditions scs1 = new SearchConditions();
				scs1.addCondition("get_pro_code",proget.getOriCode(),SearchCondition.OP_EQUAL);
				List<LogicProGetApplyDO> apply = logicProGetApplyDAO.find(scs1);
				LogicProGetApplyItemDO  applydo = new LogicProGetApplyItemDO();
				applydo.setGetProId(apply.get(0).getId());
				List<LogicProGetApplyItemDO> applyitem = logicProGetApplyItemDAO.findListByExample(applydo);
				boolean bf = true;
				for(int i=0;i<applyitem.size();i++){
					Double allquantity=(allQuantity(apply.get(0).getGetProCode(),applyitem.get(i).getCode())==null?0.0:allQuantity(apply.get(0).getGetProCode(),applyitem.get(i).getCode()));
					if(allquantity<applyitem.get(i).getJquantuty()){
						bf = false;
						break;
					}
				}
				if(bf){
					if(apply!=null&&!apply.isEmpty()&&apply.size()>0){
						apply.get(0).setIsnotck(2);
					}
				}else{
					if(apply!=null&&!apply.isEmpty()&&apply.size()>0){
						apply.get(0).setIsnotck(1);
					}
				}
				int j = logicProGetApplyDAO.updateLogicProGetApplyDO(apply.get(0));
				if(j!=1){
					throw new SyBaseException("提交失败");
				}
				
				result = logicProGetDAO.updateLogicProGetDO(curAP);
				for(LogicProGetItemDO item : swItemList){
					item.setYcksl((item.getYcksl()==null?0.0:item.getYcksl())+(item.getActureQuantity()==null?0.0:item.getActureQuantity()));
					logicProGetItemDAO.updateLogicProGetItemDO(item);
				}
				if(1==result){
					curAP = logicProGetDAO.findLogicProGetDOByPrimaryKey(curAP.getId());
					LogicProGetItemDO progetitem=new LogicProGetItemDO();
					progetitem.setGetProId(curAP.getId());
					swItemList=logicProGetItemDAO.findListByExample(progetitem);
					if(swItemList!=null&&!swItemList.isEmpty()&&swItemList.size()>0){
						for(int i=0;i<swItemList.size();i++){
							if("Y".equals(swItemList.get(i).getOpenBatch())){
								if(swItemList.get(i).getItemBatch() != null && !"".equals(swItemList.get(i).getItemBatch().trim())){
									List<LogicProGetItemBatchDO> itemBatchDOs = JSONArray.parseArray(swItemList.get(i).getItemBatch(),LogicProGetItemBatchDO.class);
									for (int k = 0; k < itemBatchDOs.size(); k++) {
									LogicWhAffDO lwhaff = new LogicWhAffDO();
									lwhaff.setBillCode(curAP.getGetProCode());
									lwhaff.setBillType("LL");// 设置为销售编码的头字符
									lwhaff.setWhCode(curAP.getWhCode());
									lwhaff.setWhname(curAP.getWhName());
									lwhaff.setBatch(itemBatchDOs.get(k).getBatch());
									lwhaff.setUnit(swItemList.get(i).getUnit());
									lwhaff.setJunit(swItemList.get(i).getJunit());
									lwhaff.setCode(swItemList.get(i).getCode());
									lwhaff.setName(swItemList.get(i).getName());
									lwhaff.setSpec(swItemList.get(i).getSpec());
									lwhaff.setStatus(itemBatchDOs.get(k).getStatus());// 库存等级
									lwhaff.setQuantity(-itemBatchDOs.get(k).getQuantuty());// ?
									lwhaff.setJquantity(-itemBatchDOs.get(k).getActureQuantity());
									logicWhAffStockService.updateWhAffstockQuantity(lwhaff,SessionUtil.getUser(request),false);
									}
								}
							}else{
								LogicWhAffDO lwhaff = new LogicWhAffDO();
								lwhaff.setBillCode(curAP.getGetProCode());
								lwhaff.setBillType("LL");// 设置为销售编码的头字符
								lwhaff.setWhCode(curAP.getWhCode());
								lwhaff.setWhname(curAP.getWhName());
								lwhaff.setBatch("NoBatch");
								lwhaff.setUnit(swItemList.get(i).getUnit());
								lwhaff.setJunit(swItemList.get(i).getJunit());
								lwhaff.setCode(swItemList.get(i).getCode());
								lwhaff.setName(swItemList.get(i).getName());
								lwhaff.setSpec(swItemList.get(i).getSpec());
								lwhaff.setStatus(swItemList.get(i).getStatus());// 库存等级
								lwhaff.setQuantity(-swItemList.get(i).getQuantuty());// ?
								lwhaff.setJquantity(-swItemList.get(i).getActureQuantity());
								logicWhAffStockService.updateWhAffstockQuantity(lwhaff,SessionUtil.getUser(request),false);
							}
						}
					}
				}else{
					throw new SyBaseException("您修改的的行数据发生改变！请重新打开查看");
				}
			}			
		} catch (Exception e) {;
			logger.error(e.getMessage(), e);
			throw new SyBaseException(GlobalResLoader.getOpfailed()
					+ e.getMessage());
		}
	}

	/**
	 * 查询当前领料出库单中某一物料的已出库数量和本次出库数量之和
	 * @param code 领料申请单编码
	 * @param macode 领料单物料编码
	 * @return
	 */
	private Double allQuantity(String code,String macode){
		//logicProGetService
		SearchConditions scs = new SearchConditions();
		scs.addCondition("ori_code",code,SearchCondition.OP_EQUAL);
		List<LogicProGetDO> apply = logicProGetDAO.find(scs);
		List<String> ids = new ArrayList<String>();
		Double allquantity=0.0;
		if(apply!=null&&!apply.isEmpty()&&apply.size()>0){
			for(int i=0;i<apply.size();i++){
				ids.add(apply.get(i).getId());
			}
			SearchConditions scs1 = new SearchConditions();
			scs1.clearCondition();
			scs1.addCondition("item.code",macode,SearchCondition.OP_EQUAL);
			scs1.addCondition("item.get_pro_id", ids);
			allquantity=logicProGetItemDAO.sumQuantity(scs1);
		}
		return allquantity;
	}

	@Override
	public Integer deleteBizRemoved(String id) throws SyBaseException {
		// TODO Auto-generated method stub
		return null;
	}
}
